package com.wshl.aijiuunion.controller.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.lzy.okgo.OkGo;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.utils.DialogUtil;
import com.wshl.aijiuunion.utils.GlideUtils;
import com.wshl.aijiuunion.utils.share.LoginOutUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created buy 风凊扬 on 2019/10/29 0029
 * 个人资料
 */
public class PersonDataActivity extends TakePhotoActivity implements DialogUtil.OnDialogConfirm, DialogUtil.OnBottomDilogClick {


    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    private CompressConfig compressConfig;
    private TakePhoto takePhoto;
    private Uri imageUri;
    private CropOptions cropOptions;
    private String imgurl;

    private RequestModel personModel;
    private String nickname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_persondata);
        ButterKnife.bind(this);
        BarUtils.setWhiteStatusBarForActivity(this);
        LogUtils.i("persondata--onCreate");
        //图片选择器
        takePhoto = getTakePhoto();
        //压缩图片(压缩到100k以内)
        compressConfig = new CompressConfig.Builder().setMaxSize(200 * 1024).create();
        // takePhoto.onEnableCompress(compressConfig, false);//设置压缩时参数,不显示压缩时的对话框
        //图片裁剪方式
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();

        initView();
        personModel = new RequestModel();
        DialogUtil.setOndialgConfirm(this);
        DialogUtil.setOnBottomDilogClick(this);


    }

    private void initView() {
        tvTopTitle.setText("个人信息");
        SPUtils instance = SPUtils.getInstance();
        String avatar = instance.getString(GlobConstant.AVATAR);
        nickname = instance.getString(GlobConstant.NIAKNAME);

        tvNickname.setText(nickname);
        if (!TextUtils.isEmpty(avatar)) {
            if (!avatar.startsWith("http")) {
                GlideUtils.loadCircleImage(PersonDataActivity.this, NetUrl.IMG + avatar, imgHead);
            } else {
                GlideUtils.loadCircleImage(PersonDataActivity.this, avatar, imgHead);
            }

        }
    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        String originalPath = result.getImage().getOriginalPath();
        String compressPath = result.getImage().getCompressPath();//压缩路径
        LogUtils.e("头像路径:" + originalPath);
        LogUtils.e("头像压缩路径:" + compressPath);
        GlideUtils.loadCircleImage(PersonDataActivity.this, compressPath, imgHead);

        if (!TextUtils.isEmpty(compressPath)) {
            UploadImg(compressPath);
        }


    }

    private void UploadImg(String compressPath) {

        personModel.uploadImg(PersonDataActivity.this, compressPath, new RequestCallback() {
            @Override
            public void onSuccess(String response) {
                imgurl = response;

                if (!TextUtils.isEmpty(imgurl)) {
                    //编辑用户信息
                    UserEdit(imgurl, "");
                }
            }

            @Override
            public void onError(int code) {
                LogUtils.e("上传图片失败:" + code);
            }

            @Override
            public void onIntentError() {

            }
        });

    }

    private void UserEdit(final String imgurl, final String nickname) {


        personModel.userEdit(PersonDataActivity.this, imgurl, nickname, new RequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("code")) {
                        String code = jsonObject.getString("code");
                        switch (code) {
                            case GlobConstant.REQUESTSUCCESS:
                                SPUtils instance = SPUtils.getInstance();
                                if (!TextUtils.isEmpty(imgurl)) {
                                    instance.put(GlobConstant.AVATAR, imgurl);
                                }

                                if (!TextUtils.isEmpty(nickname)) {
                                    instance.put(GlobConstant.NIAKNAME, nickname);
                                }

                                break;
                            case GlobConstant.REQUESTERROR:
                                LoginOutUtils.reLogin(PersonDataActivity.this);
                                break;
                            default:

                                break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int code) {
                LogUtils.e("修改用户信息失败:" + code);
            }

            @Override
            public void onIntentError() {

            }
        });

    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void setConfirm() {


    }

    @Override
    public void setCancel() {

    }

    @Override
    public void getInput(String input) {
        if (!TextUtils.isEmpty(input)) {

            tvNickname.setText(input);
            UserEdit("", input);
        }
    }

    @OnClick({R.id.img_back, R.id.img_head, R.id.tv_nickname, R.id.tv_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                PersonDataActivity.this.finish();
                break;
            case R.id.img_head:
                DialogUtil.showBottomDialog(PersonDataActivity.this, "拍照", "相册", "", "#57BE6A", "#57BE6A", "#57BE6A");
                break;
            case R.id.tv_nickname:

                DialogUtil.showNormaldialog(PersonDataActivity.this, "请输入昵称", true, true);
                break;
            case R.id.tv_address:

                String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
                if (TextUtils.isEmpty(token)) {
                    ToastUtils.showShort("请登录");
                    return;
                }
                Intent intent = new Intent(PersonDataActivity.this, WebActivity.class);
                intent.putExtra(GlobConstant.WEBURL, NetUrl.ADDRESSLIST + token);
                ActivityUtils.startActivity(intent);
                break;
        }
    }

    //获取头像
    private void getImage(final String title) {
        XXPermissions.with(this)
                .constantRequest() //设置被拒绝后继续申请，直到用户授权或者永久拒绝
                // .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                .permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {

                        File file = new File(GlobConstant.SDCARD_DIR, GlobConstant.IMAGE_CACHE_DIR + System.currentTimeMillis() + ".png");
                        if (!file.getParentFile().exists())
                            file.getParentFile().mkdirs();
                        imageUri = Uri.fromFile(file);
                        if (title.equals("拍照")) {
                            takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);

                        } else if (title.equals("相册")) {

                            takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                        }
                        takePhoto.onEnableCompress(compressConfig, false);//设置压缩时参数,不显示压缩时的对话框

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //如果权限被永久禁止,quick值为true
                        //让用户手动打开权限设置
                        if (quick) {
                            DialogUtil.showNormaldialog(PersonDataActivity.this, "请手动打开权限", false, true);
                            DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                                @Override
                                public void setConfirm() {
                                    XXPermissions.gotoPermissionSettings(PersonDataActivity.this);
                                }

                                @Override
                                public void setCancel() {
                                    PersonDataActivity.this.finish();

                                }

                                @Override
                                public void getInput(String input) {

                                }
                            });

                        }

                    }
                });
    }

    @Override
    public void setTitle1(String title1) {

        getImage(title1);

    }

    @Override
    public void setTitle2(String title2) {
        getImage(title2);
    }

    @Override
    public void setTitle3(String title3) {

        ToastUtils.showShort(title3);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelAll();
    }
}
